package com.weilele.mvvm.oauth

import androidx.annotation.WorkerThread
import okhttp3.OkHttpClient
import okhttp3.Request
import org.apache.oltu.oauth2.client.OAuthClient
import org.apache.oltu.oauth2.client.request.OAuthClientRequest
import org.apache.oltu.oauth2.common.message.types.GrantType

object OAuth2Util {
    data class OAuthBean(
        var accessToken: String?,
        var refreshToken: String?,
        var tokenType: String?,
        var scope: String?,
        var expiresIn: Long?
    )


    /**
     * 用户登录
     */
    @WorkerThread
    fun login(
        clientId: String,
        secret: String,
        tokenUrl: String?,
        phoneStr: String?,
        pswStr: String?,
        grantType: GrantType = GrantType.PASSWORD
    ): OAuthBean {
        val request = OAuthClientRequest
            .tokenLocation(tokenUrl)
            .setClientId(clientId)
            .setClientSecret(secret)
            .setUsername(phoneStr)
            .setPassword(pswStr)
            .setGrantType(grantType)
            .buildBodyMessage()
        val client = OAuthClient(OAuthOkHttpClient())
        val accessTokenResponse = client.accessToken(request)
        val oauthToken = OAuthBean(
            accessTokenResponse?.accessToken,
            accessTokenResponse?.refreshToken,
            accessTokenResponse?.tokenType,
            accessTokenResponse?.scope,
            accessTokenResponse?.expiresIn
        )
        client.shutdown()
        return oauthToken
    }

    //{
//    │     "access_token": "159b92f3-4ed0-4760-8ab8-f193dbcd34cf",
//    │     "token_type": "bearer",
//    │     "refresh_token": "506a9f84-925b-4d56-8c72-34e51ecc753d",
//    │     "expires_in": 2999999,
//    │     "scope": "read write"
//    │   }

    @Deprecated("测试使用")
    private fun addInterceptor(builder: OkHttpClient.Builder?, tokenResponse: OAuthBean) {
        builder?.addInterceptor {
            val oldRequest = it.request()
            val token = tokenResponse.accessToken
            if (token == null) {
                it.proceed(oldRequest)
            } else {
                val newRequest = oldRequest.newBuilder()
                addTokenHead(newRequest, tokenResponse)
                it.proceed(newRequest.build())
            }
        }
    }

    /**
     * 添加token请求头
     */
    fun addTokenHead(request: Request.Builder, tokenResponse: OAuthBean?) {
        tokenResponse ?: return
        request.removeHeader("Authorization")
        request.addHeader(
            "Authorization",
            "${tokenResponse.tokenType} ${tokenResponse.accessToken}"
        )
    }
}